<template>
  <div>
    <el-autocomplete
      class="inline-input"
      popper-class="table-autocomplete"
      :style="{ width: width + 'px' }"
      :class="[ width ? '' : 'wid220' ]"
      v-model="inputValue"
      :clearable="clearable"
      @clear="clear"
      @focus="inputFocus"
      ref="searchSelect"
      :fetch-suggestions="querySearchAsync"
      :placeholder="placeholder"
      @keydown.native="handleKeyDown"
    >
      <template slot-scope="{ item }">
        <div class="main_table" @click.stop>
          <el-table 
            :data="item"
            ref="multipleTable"
            max-height="400"
            @row-click="rowClick"
            :row-class-name="getRowClass"
            highlight-current-row
          >
            <el-table-column width="210" prop="name" label="商品名称" class-name="main_hei">
              <template slot-scope="{row}">
                <p class="activeColor">{{ `${row.goods_each.name}【${row.goods_each.spu_name}】` }}</p>
                <p class="spuCode">{{ row.goods_each.goods_spu_code }}</p>
              </template>
            </el-table-column>
            <el-table-column width="60" prop="goods_each.unit" label="单位"></el-table-column>
            <el-table-column width="100" prop="goods_each.detail" label="描述"></el-table-column>
            <el-table-column width="200" prop="goods_each.category_name" label="商品分类" class-name="main_hei"></el-table-column>
            <el-table-column width="160" prop="goods_each.inventory_num" label="现有库存"></el-table-column>
            <el-table-column width="140" prop="equal_star" label="下单指数">
              <template slot-scope="{ row }">
                <el-rate
                  v-model="row.goods_each.star.equal_star"
                  disabled
                  text-color="#ff9900"
                >
                </el-rate>
              </template>
            </el-table-column>
            <el-table-column width="100" prop="upper_star" label="趋势">
              <template slot-scope="{ row }">
                <svg-icon :icon-class="getTrendIconClass(row)"></svg-icon>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-autocomplete>
  </div>
</template>

<script>
import { goodsSupList } from "@/api/currency";
import { packApi } from "@/utils/public";
export default {
  props: {
    placeholder: {
      type: String,
      default: "商品名称/助记码/编码"
    },
    isInventory:{
      type: Boolean,
      default: false
    },
    clearable:{
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    parentQuerySearchAsync: {
      type: Function,
    },
    tableList: {
      type: Array,
      default: ()=> []
    }
  },
  data() {
    return {
      currentIndex: 0,  // 用于绑定当前选中的行
    };
  },
  computed: {
    inputValue: {
      get() {
        return this.value;
      },
      set(e) {
        // 当inputValue改变时，向外触发input事件并传递新值e
        this.$emit('input',e);
      },
    },
  },
  methods: {
    setCurrent(row) {
      this.$refs.multipleTable.setCurrentRow(row);
    },
    handleKeyDown(event) {
      if(!this.tableList.length) return;
      // 监听上下键
      if (event.keyCode === 40 || event.keyCode === 38) {
        if (event.keyCode === 40 && this.currentIndex < this.tableList.length - 1) {
          this.currentIndex++;
        } else if (event.keyCode === 38 && this.currentIndex > 0) {
          this.currentIndex--;
        }
        // 更新选中行
        this.$refs.multipleTable.setCurrentRow(this.tableList[this.currentIndex]);
        this.scrollToCurrentRow();
      }
      if(event.keyCode=== 13 && this.tableList[this.currentIndex]) {
        this.rowClick(this.tableList[this.currentIndex]);
      }
    },
    scrollToCurrentRow() {
      const table = this.$refs.multipleTable.$el.querySelector('.el-table__body-wrapper');
      if (!table) return;
      const rows = table.querySelectorAll('.el-table__row');
      const selectedRow = rows[this.currentIndex];
      if (selectedRow) {
        // 获取当前选中行的顶部位置
        const rowTop = selectedRow.offsetTop;
        const rowHeight = selectedRow.offsetHeight;
        const tableScrollTop = table.scrollTop;
        const tableHeight = table.clientHeight;
        // 如果选中行在可视区域外，滚动到该行
        if (rowTop < tableScrollTop) {
          table.scrollTop = rowTop; // 滚动到行上方
        } else if (rowTop + rowHeight > tableScrollTop + tableHeight) {
          table.scrollTop = rowTop + rowHeight - tableHeight; // 滚动到行下方
        }
      }
    },
    // 提取出判断逻辑
    getTrendIconClass(row) {
      const { upper_star, equal_star } = row.goods_each.star;
      if (upper_star > equal_star) {
        return 'decline';  // 趋势下降图标
      } else if (upper_star < equal_star) {
        return 'rise';  // 趋势上升图标
      }
      return 'equality';  // 没有趋势变化
    },
    getRowClass({row}) {
      if(this.isInventory && row.is_inventory == 2) {
        return "opacity"
      }
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      this.currentIndex = 0;
      if (this.parentQuerySearchAsync && typeof this.parentQuerySearchAsync === 'function') {
        this.parentQuerySearchAsync(queryString, cb);
        return;
      }
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = packApi({
        name: queryString.trim(),
      });
      goodsSupList(data).then(res => {
        if (res.errcode == 0) {
          cb([res.data.goods]);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 清空
    clear() {
      this.$emit('input','');
      this.$emit("clear");
    },
    // 获取焦点
    inputFocus() {
      this.$emit("focus");
    },
    // 选中
    focus() {
      this.$refs["searchSelect"].focus();
    },
    // 失去焦点
    blur() {
      this.$refs.searchSelect.$children[0].blur();
    },
    // 表格列点击
    rowClick(row, column, event) {
      this.closeActived();
      this.$emit("select", row);
    },
    // 关闭选择框
    closeActived() {
      this.$nextTick(()=> {
        this.currentIndex = 0;
        this.$refs.searchSelect.activated = false;
        this.$refs.searchSelect.suggestions = [];
        this.$refs.searchSelect.highlightedIndex = -1;
      });
    },
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
/deep/.newAutocomplete{
  width: 500px !important;
}
/deep/.el-autocomplete-suggestion li {
  padding: 0;
  width: auto;
}
.spuCode {
  font-size: 12px;
  color: rgba(0,0,0,0.55);
}
</style>
